<template>
  <div class="databaselist">
    <div class="topTitle">
      <span class="title">题库管理</span>
      <el-button
        type="primary"
        size="default"
        style="font-size: 12px"
        @click="dialogVisible = true"
        v-show="isButton(38)"
        >创建题库</el-button
      >
    </div>
    <div class="operate">
      <span>题库名称:</span>
      <!-- 题库名称input -->
      <div class="key">
        <el-input
          v-model="params.key"
          class="w-50 m-2 keyInput"
          placeholder="请输入题库名称"
          clearable
        />
      </div>
      <span>创建人:</span>
      <!-- 题库名称input -->
      <div class="admin">
        <el-input
          v-model="params.admin"
          class="w-50 m-2 keyInput"
          placeholder="请输入创建人"
          clearable
        />
      </div>
      <el-checkbox
        v-model="params.ismy"
        true-label="1"
        false-label="0"
        label="只看我创建的"
        size="large"
      />
      <!-- 查询按钮 -->
      <el-button
        type="primary"
        style="font-size: 12px; margin-left: 10px; width: 60px; height: 30px"
        @click="inquire"
        >查询</el-button
      >
      <!-- 批量删除按钮 -->
      <el-button
        type="danger"
        :disabled="multipleSelection.length === 0 ? true : false"
        @click="dels"
        style="font-size: 12px; margin-left: 10px; width: 70px; height: 30px"
        v-show="isButton(70)"
        >批量删除</el-button
      >
    </div>
    <div class="table">
      <!-- 表格 -->
      <el-table
        ref="multipleTableRef"
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        :header-cell-style="{ backgroundColor: '#fafafa' }"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="题库" width="450">
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="toQuestion(scope.row)"
              size="small"
            >
              {{ scope.row.title }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          property="counts"
          label="题量数目"
          show-overflow-tooltip
        />
        <el-table-column
          property="addtime"
          label="创建时间"
          show-overflow-tooltip
          ><template #default="scope">
            <span>{{ scope.row.addtime.substr(0, 16) }}</span>
          </template></el-table-column
        >
        <el-table-column
          label="创建人"
          property="admin"
          show-overflow-tooltip
        />
        <el-table-column fixed="right" label="操作" width="150">
          <template #default="scope">
            <el-button
              link
              type="primary"
              size="small"
              @click="toQuestion(scope.row)"
            >
              试题
            </el-button>
            <!-- 编辑按钮 -->
            <el-button
              link
              text
              type="primary"
              @click="upd(scope.row, scope.row.limits)"
              size="small"
              v-show="isButton(38)"
            >
              编辑
            </el-button>

            <!-- 删除按钮 -->
            <el-button
              link
              type="primary"
              size="small"
              @click.prevent="deleteRow(scope.row.id)"
              v-show="isButton(70)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="demo-pagination-block">
        <el-pagination
          v-model:currentPage="params.page"
          v-model:page-size="params.psize"
          :page-sizes="[10, 20, 30, 100]"
          :small="small"
          :disabled="disabled"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="counts"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 弹出框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dynamicValidateForm.id === 0 ? '题库添加' : '题库修改'"
      width="45%"
      :close-on-click-modal="false"
      :before-close="handleClose"
      v-if="dialogVisible"
    >
      <div>
        <el-form
          ref="formRef"
          :model="dynamicValidateForm"
          label-width="120px"
          class="demo-dynamic"
        >
          <el-form-item
            prop="title"
            label="题库名称"
            :rules="{
              required: true,
              message: '请输入题库名称',
              trigger: 'blur',
            }"
          >
            <div style="width: 350px">
              <el-input v-model="dynamicValidateForm.title" clearable />
            </div>
          </el-form-item>

          <el-form-item prop="isshow" label="被他人使用">
            <div style="width: 200px">
              <el-radio-group v-model="dynamicValidateForm.isshow" class="ml-4">
                <el-radio :label="1" size="large">允许所有老师使用</el-radio>
                <el-radio :label="2" size="large">不允许任何老师使用</el-radio>
                <el-radio :label="3" size="large" @click="toTeacher">
                  <el-badge
                    :value="dynamicValidateForm.limits.length"
                    :hidden="dynamicValidateForm.isshow != 3 ? true : false"
                    class="item"
                    type="primary"
                  >
                    允许部分老师使用
                  </el-badge>
                </el-radio>
              </el-radio-group>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="add">确认</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 点击允许部分老师使用弹出对话框 -->
    <div class="limits">
      <el-dialog
        v-model="dialogVisibleSon"
        :modal="false"
        top="5vh"
        title="可见老师"
        width="48%"
        :close-on-click-modal="false"
        v-if="dialogVisibleSon"
      >
        <div style="padding: 0 10px">
          <div style="margin-bottom: 20px">
            <span style="margin-right: 10px">部门</span>
            <el-select
              v-model="paramsTeacher.depid"
              @change="depidChange"
              clearable
              class="m-2"
              placeholder="请选择"
            >
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </div>
          <div>
            <!-- 穿梭框 -->
            <el-transfer
              @left-check-change="leftCheckChange"
              @right-check-change="rightCheckChange"
              v-model="dynamicValidateForm.limits"
              :titles="['未选', '已选']"
              v-loading="loadingTeacher"
              ref="server"
              :props="{
                key: 'id',
                label: 'name',
              }"
              :data="limitsData"
            />
          </div>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button
              @click="
                () => {
                  dialogVisibleSon = false;
                }
              "
              >取消</el-button
            >
            <el-button type="primary" @click="dialogVisibleSon = false"
              >确定</el-button
            >
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, toRefs, ref, watchEffect, watch, onMounted } from "vue";
import { ElTable, ElMessage, ElMessageBox } from "element-plus";
// 引入权限按钮是否显示
import { isButton } from "../../utils/isButton";
import {
  getDatabaseList,
  getDelete,
  postDeletes,
  getTeacherList,
  getDepartmentList,
  postAdd,
} from "../../apis/databaselist/databaselist";
import { useRouter } from "vue-router";

// 跳转
const router = useRouter();

const data: any = reactive({
  tableData: [],
  params: {
    page: 1,
    psize: 10,
    key: "",
    admin: "",
    ismy: 0,
  },
  departmentParams: {
    page: 1,
    psize: 500,
  },
  server: <any>[],
  dynamicValidateForm: <any>{ id: 0, title: "", isshow: 1, limits: [] },
  // 请求老师列表信息
  paramsTeacher: { page: 1, psize: 500, depid: null },
  // 选择部分老师弹出框
  dialogVisibleSon: false,
  // 穿梭框
  limitsData: [],
  // 添加弹出框
  dialogVisible: false,
  // 添加弹出框内表单内容
  options: [],
  // 加载
  loading: true,
  loadingTeacher: true,
  small: false,
  disabled: false,
  // 选中数据
  multipleSelection: [],
  counts: 0,
});
// 解构data内的列表数据
const {
  counts,
  multipleSelection,
  disabled,
  small,
  loadingTeacher,
  loading,
  options,
  dialogVisible,
  tableData,
  params,
  departmentParams,
  dynamicValidateForm,
  server,
  paramsTeacher,
  dialogVisibleSon,
  limitsData,
} = toRefs(data);

// 部门内容改变
const depidChange = (e: any) => {
  paramsTeacher.value.depid = e;
  loadingTeacher.value = true;
  teacherList(paramsTeacher.value);
};
// 三次封装列表接口
const databaseList = async (params: any) => {
  const res: any = await getDatabaseList(params);
  if (res.errCode === 10000) {
    tableData.value = res.data.list;
    loading.value = false;
    counts.value = res.data.counts;
  } else {
    ElMessage.error(res.errMsg);
  }
};

// 复选框内容改变事件
const handleSelectionChange = (val: any) => {
  multipleSelection.value = val;
};
// 点击删除
const deleteRow = (id: number) => {
  ElMessageBox.confirm("此操作将永久删除该文件, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      loading.value = true;
      const res: any = await getDelete(id);
      if (res.errCode === 10000) {
        ElMessage({
          type: "success",
          message: "删除成功",
        });
        databaseList(params.value);
      } else {
        ElMessage({
          type: "info",
          message: res.errMsg,
        });
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除！",
      });
    });
};
// 点击批量删除
const dels = () => {
  const ids = multipleSelection.value.map((item:any) => item.id);
  ElMessageBox.confirm("此操作将永久删除选中的文件, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      loading.value = true;
      const res: any = await postDeletes(ids);
      if (res.errCode === 10000) {
        ElMessage({
          type: "success",
          message: "删除成功",
        });
        databaseList(params.value);
      } else {
        ElMessage({
          type: "info",
          message: res.errMsg,
        });
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除！",
      });
    });
};
// 点击查询
const inquire = () => {
  loading.value = true;
  databaseList(params.value);
};

// 点击选择部分老师可见弹出对话框
const toTeacher = () => {
  dialogVisibleSon.value = true;
  teacherList(paramsTeacher.value);
  departmentList(departmentParams.value);
};

// 穿梭框左边内容改变时触发
const leftCheckChange = (key: any, keys: any) => {
  server.value.addToRight();
};
// 穿梭框右边内容改变时触发
const rightCheckChange = (key: any) => {
  server.value.addToLeft();
};

// 请求老师列表信息
const teacherList = async (paramsTeacher: any) => {
  const res: any = await getTeacherList(paramsTeacher);
  if (res.errCode === 10000) {
    limitsData.value = res.data.list;
    loadingTeacher.value = false;
  } else {
    ElMessage.error(res.errMsg);
  }
};
// 请求部门列表信息
const departmentList = async (departmentParams: any) => {
  const res: any = await getDepartmentList(departmentParams);
  if (res.errCode === 10000) {
    options.value = res.data.list;
  } else {
    ElMessage.error(res.errMsg);
  }
};
// 数值数组  转  对象数组
const limitsArr = (arr: any) => {
  return arr.map((item: any) => ({ id: item }));
};
// 清空
const empty = () => {
  dynamicValidateForm.value = {
    id: 0,
    title: "",
    isshow: 1,
    limits: <any>[],
  };
};
// 点击取消
const cancel = () => {
  dialogVisible.value = false;
  empty();
};
// 添加弹出框点击x关闭
const handleClose = (done: () => void) => {
  dialogVisible.value = false;
  empty();
};
// 点击确定添加
const add = async () => {
  if (!data.dynamicValidateForm.title) {
    ElMessage({ message: "请输入题库名称！", duration: 1500 });
    return;
  }
  dialogVisible.value = false;
  loading.value = true;
  const addParams = {
    ...dynamicValidateForm.value,
    limits: limitsArr(dynamicValidateForm.value.limits),
  };
  const res: any = await postAdd(addParams);
  if (res.errCode === 10000) {
    ElMessage({
      message: "添加成功",
      type: "success",
    });
    databaseList(params.value);
    dynamicValidateForm.value = {
      id: 0,
      title: "",
      isshow: 1,
      limits: <any>[],
    };
  } else {
    ElMessage.error(res.errMsg);
  }
};

onMounted(() => {
  // 调用列表接口
  databaseList(params.value);
});
// 点击编辑修改
const upd = (data: any, limits: any) => {
  dialogVisible.value = true;
  // console.log(111111,data, limits);
  dynamicValidateForm.value = {
    ...dynamicValidateForm.value,
    id: data.id,
    title: data.title,
    isshow: data.isshow,
  };
};
// 点击查看试题
const toQuestion = (data: any) => {
  const datas = JSON.stringify(data);
  router.push({ name: "databasequestionlist", query: { data: datas } });
};
// 每页多少条内容改变
const handleSizeChange = (val: number) => {
  params.value.psize = val;
  databaseList(params.value);
  loading.value = true;
};
// 页码内容改变
const handleCurrentChange = (val: number) => {
  params.value.page = val;
  databaseList(params.value);
  loading.value = true;
};
// 监听admin
watch(
  () => data.params.ismy,
  (newValue: number, oldValue: any) => {
    if (newValue == 1) {
      params.value.admin = "";
    }
  }
);
// 钩子函数
watchEffect(() => {
  if (params.value.admin !== "") {
    params.value.ismy = 0;
  }
});
</script>

<style lang="less" scoped>
@import url("../../static/css/databaselist/databaselist.css");
</style>
